<template>
  <div class="login_container">
    <el-dialog v-model="userStore.visible" title="用户登录" @close="close">
      <el-row>
        <el-col :span="12">
          <div class="login">
            <div v-show="scene == 0">
              <el-form :model="loginParam" :rules="rules" ref="form">
                <el-form-item prop="phone">
                  <el-input placeholder="请输入手机号码" :prefix-icon="User" v-model="loginParam.phone"></el-input>
                </el-form-item>
                <el-form-item prop="code">
                  <el-input placeholder="请输入短信验证码" :prefix-icon="Lock" v-model="loginParam.code"></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button :disabled="!isPhone || flag ? true : false">
                    <CountDown v-if="flag" :flag="flag" @getFlag="getFlag" />
                    <span v-else @click="getCode">获取验证码</span>
                  </el-button>
                </el-form-item>
              </el-form>
              <el-button style="width:100%;" type="primary" size="default"
                :disabled="!isPhone || loginParam.code.length !== 6" @click="login">用户登录</el-button>
              <div class="bottom" @click="changeScene">
                <p>微信扫码登录</p>
                <svg t="1739448510277" class="icon" viewBox="0 0 1024 1024" version="1.1"
                  xmlns="http://www.w3.org/2000/svg" p-id="9023" width="32" height="32">
                  <path
                    d="M352.814545 385.396364m-33.512727 0a33.512727 33.512727 0 1 0 67.025455 0 33.512727 33.512727 0 1 0-67.025455 0Z"
                    fill="#50B674" p-id="9024"></path>
                  <path
                    d="M502.690909 384.465455m-33.512727 0a33.512727 33.512727 0 1 0 67.025454 0 33.512727 33.512727 0 1 0-67.025454 0Z"
                    fill="#50B674" p-id="9025"></path>
                  <path
                    d="M576.232727 534.341818m-23.272727 0a23.272727 23.272727 0 1 0 46.545455 0 23.272727 23.272727 0 1 0-46.545455 0Z"
                    fill="#50B674" p-id="9026"></path>
                  <path
                    d="M694.458182 536.203636m-23.272727 0a23.272727 23.272727 0 1 0 46.545454 0 23.272727 23.272727 0 1 0-46.545454 0Z"
                    fill="#50B674" p-id="9027"></path>
                  <path
                    d="M512 0C229.003636 0 0 229.003636 0 512s229.003636 512 512 512 512-229.003636 512-512S794.996364 0 512 0z m-87.505455 630.225455c-26.996364 0-48.407273-5.585455-75.403636-11.17091l-75.403636 37.236364 21.410909-64.232727c-53.992727-37.236364-85.643636-85.643636-85.643637-145.221818 0-102.4 96.814545-182.458182 215.04-182.458182 105.192727 0 198.283636 64.232727 216.901819 150.807273-6.516364-0.930909-13.963636-0.930909-20.48-0.93091-102.4 0-182.458182 76.334545-182.458182 170.356364 0 15.825455 2.792727 30.72 6.516363 44.683636-7.447273 0-13.963636 0.930909-20.48 0.93091z m314.647273 75.403636l15.825455 53.992727-58.647273-32.581818c-21.410909 5.585455-42.821818 11.170909-64.232727 11.170909-102.4 0-182.458182-69.818182-182.458182-155.461818s80.058182-155.461818 182.458182-155.461818c96.814545 0 182.458182 69.818182 182.458182 155.461818 0 47.476364-31.650909 90.298182-75.403637 122.88z"
                    fill="#50B674" p-id="9028"></path>
                </svg>
              </div>
            </div>
            <div class="webchat" v-show="scene == 1">
              <div id="login_container"></div>
              <div class="phone" @click="handler">
                <p>手机短信验证码登录</p>
                <svg t="1739605100843" class="icon" viewBox="0 0 1024 1024" version="1.1"
                  xmlns="http://www.w3.org/2000/svg" p-id="1533" width="16" height="16">
                  <path
                    d="M820.409449 797.228346q0 25.19685-10.07874 46.866142t-27.716535 38.299213-41.322835 26.204724-50.897638 9.574803l-357.795276 0q-27.212598 0-50.897638-9.574803t-41.322835-26.204724-27.716535-38.299213-10.07874-46.866142l0-675.275591q0-25.19685 10.07874-47.370079t27.716535-38.80315 41.322835-26.204724 50.897638-9.574803l357.795276 0q27.212598 0 50.897638 9.574803t41.322835 26.204724 27.716535 38.80315 10.07874 47.370079l0 675.275591zM738.771654 170.330709l-455.559055 0 0 577.511811 455.559055 0 0-577.511811zM510.992126 776.062992q-21.165354 0-36.787402 15.11811t-15.622047 37.291339q0 21.165354 15.622047 36.787402t36.787402 15.622047q22.173228 0 37.291339-15.622047t15.11811-36.787402q0-22.173228-15.11811-37.291339t-37.291339-15.11811zM591.622047 84.661417q0-8.062992-5.03937-12.598425t-11.086614-4.535433l-128 0q-5.03937 0-10.582677 4.535433t-5.543307 12.598425 5.03937 12.598425 11.086614 4.535433l128 0q6.047244 0 11.086614-4.535433t5.03937-12.598425z"
                    p-id="1534"></path>
                </svg>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="leftContent">
            <div class="top">
              <div class="item">
                <img src="../../assets/images/code_app.png" alt="">
                <svg t="1739448510277" class="icon" viewBox="0 0 1024 1024" version="1.1"
                  xmlns="http://www.w3.org/2000/svg" p-id="9023" width="16" height="16">
                  <path
                    d="M352.814545 385.396364m-33.512727 0a33.512727 33.512727 0 1 0 67.025455 0 33.512727 33.512727 0 1 0-67.025455 0Z"
                    fill="#cdcdcd" p-id="9024"></path>
                  <path
                    d="M502.690909 384.465455m-33.512727 0a33.512727 33.512727 0 1 0 67.025454 0 33.512727 33.512727 0 1 0-67.025454 0Z"
                    fill="#cdcdcd" p-id="9025"></path>
                  <path
                    d="M576.232727 534.341818m-23.272727 0a23.272727 23.272727 0 1 0 46.545455 0 23.272727 23.272727 0 1 0-46.545455 0Z"
                    fill="#cdcdcd" p-id="9026"></path>
                  <path
                    d="M694.458182 536.203636m-23.272727 0a23.272727 23.272727 0 1 0 46.545454 0 23.272727 23.272727 0 1 0-46.545454 0Z"
                    fill="#cdcdcd" p-id="9027"></path>
                  <path
                    d="M512 0C229.003636 0 0 229.003636 0 512s229.003636 512 512 512 512-229.003636 512-512S794.996364 0 512 0z m-87.505455 630.225455c-26.996364 0-48.407273-5.585455-75.403636-11.17091l-75.403636 37.236364 21.410909-64.232727c-53.992727-37.236364-85.643636-85.643636-85.643637-145.221818 0-102.4 96.814545-182.458182 215.04-182.458182 105.192727 0 198.283636 64.232727 216.901819 150.807273-6.516364-0.930909-13.963636-0.930909-20.48-0.93091-102.4 0-182.458182 76.334545-182.458182 170.356364 0 15.825455 2.792727 30.72 6.516363 44.683636-7.447273 0-13.963636 0.930909-20.48 0.93091z m314.647273 75.403636l15.825455 53.992727-58.647273-32.581818c-21.410909 5.585455-42.821818 11.170909-64.232727 11.170909-102.4 0-182.458182-69.818182-182.458182-155.461818s80.058182-155.461818 182.458182-155.461818c96.814545 0 182.458182 69.818182 182.458182 155.461818 0 47.476364-31.650909 90.298182-75.403637 122.88z"
                    fill="#cdcdcd" p-id="9028"></path>
                </svg>
                <p>微信扫一扫关注</p>
                <p>"快速预约挂号"</p>
              </div>
              <div class="item">
                <img src="../../assets/images/code_login_wechat.png" alt="">
                <svg t="1739449372477" class="icon" viewBox="0 0 1024 1024" version="1.1"
                  xmlns="http://www.w3.org/2000/svg" p-id="11469" width="16" height="16">
                  <path
                    d="M820.409449 797.228346q0 25.19685-10.07874 46.866142t-27.716535 38.299213-41.322835 26.204724-50.897638 9.574803l-357.795276 0q-27.212598 0-50.897638-9.574803t-41.322835-26.204724-27.716535-38.299213-10.07874-46.866142l0-675.275591q0-25.19685 10.07874-47.370079t27.716535-38.80315 41.322835-26.204724 50.897638-9.574803l357.795276 0q27.212598 0 50.897638 9.574803t41.322835 26.204724 27.716535 38.80315 10.07874 47.370079l0 675.275591zM738.771654 170.330709l-455.559055 0 0 577.511811 455.559055 0 0-577.511811zM510.992126 776.062992q-21.165354 0-36.787402 15.11811t-15.622047 37.291339q0 21.165354 15.622047 36.787402t36.787402 15.622047q22.173228 0 37.291339-15.622047t15.11811-36.787402q0-22.173228-15.11811-37.291339t-37.291339-15.11811zM591.622047 84.661417q0-8.062992-5.03937-12.598425t-11.086614-4.535433l-128 0q-5.03937 0-10.582677 4.535433t-5.543307 12.598425 5.03937 12.598425 11.086614 4.535433l128 0q6.047244 0 11.086614-4.535433t5.03937-12.598425z"
                    p-id="11470" fill="#cdcdcd"></path>
                </svg>
                <p>扫一扫下载</p>
                <p>"预约挂号"APP</p>
              </div>
            </div>
            <p class="tip">尚医通官方指定平台</p>
            <p class="tip">快速挂号 安全放心</p>
          </div>
        </el-col>
      </el-row>
      <template #footer>
        <div>
          <el-button type="primary" size="default" @click="closeDialog">关闭窗口</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang=ts name="Login">
//引入倒计时组件
//@ts-ignore
import CountDown from '../countdown/index.vue'
//引入组合式API
import { reactive, ref, computed, watch } from 'vue'
//引入仓库：其中的visible可以控制Login组件对话框的显示和隐藏
//@ts-ignore
import useUserStore from '@/store/modules/user';
//引入图标
import { Lock, User } from '@element-plus/icons-vue'
//引入处理错误的函数
import { ElMessage } from 'element-plus';
//引入api中的请求方法和ts类型
//@ts-ignore
import { reqWxLogin } from '@/api/hospital'
//@ts-ignore
import type { WXLoginResponseData } from '@/api/hospital/type'
//引入路由器和路由
import { useRoute, useRouter } from 'vue-router'

//定义一个响应式数据控制倒计时子组件的显示和隐藏
let flag = ref<boolean>(false)
//控制左侧切换的响应式数据
let scene = ref<number>(0)
//定义用户仓库
let userStore = useUserStore()
//收集表单数据--手机号码
let loginParam = reactive({
  phone: '',
  code: ''
})
//获取form组件实例
let form = ref<any>()
//路由器 路由
let $route = useRoute()
let $router = useRouter()

//计算属性：计算出当前表单元素手机的内容是否是手机格式
let isPhone = computed(() => {
  const reg = /^1[3-9]\d{9}$/
  return reg.test(loginParam.phone)
})
//监视：监听场景的数值
watch(() => scene.value, (val: number) => {
  if (val === 1) {
    //调用仓库中的函数查询微信扫码的结果
    userStore.queryState()
  }
})

//倒计时子组件绑定的自定义事件的回调：当倒计时子组件倒计时结束的时候，flag变为false，父组件要拿回这个flag的值,把倒计时子组件关闭
const getFlag = (val: boolean) => {
  flag.value = val
}
//切换登陆方式的回调：
const handler = () => {
  //切换为场景0
  scene.value = 0
}
//切换登陆方式的回调
const changeScene = async () => {
  //切换为场景1
  scene.value = 1
  //发请求获取微信扫码二维码需要的参数
  //向学校服务器发送一个请求，获取微信扫码登录页面的参数
  //需要携带一个参数：告诉学校服务器用户授权成功后重定向到某一个页面
  let redirect_URL = encodeURIComponent(window.location.origin + '/wxlogin')
  let result: WXLoginResponseData = await reqWxLogin(redirect_URL)
  //生成微信扫码登录二维码的页面
  //@ts-ignore
  new WxLogin({
    self_redirect: true,//手机点击确认登录后可以在iframe内部跳转到redirect_uri
    id: "login_container",//显示二维码的容器
    appid: result.data.appid,//应用唯一标识
    scope: "snsapi_login",//当前微信扫码登录页面已经授权
    redirect_uri: result.data.redirectUri,//填写授权回调域路径，就是用户授权成功后，微信服务器向公司后台推送code地址
    state: result.data.state,//学校服务器重定向的地址携带用户信息  
    style: "black",
    href: ""
  });
}
//获取验证码
const getCode = async () => {
  //解决element按钮禁用还能点击的问题:当手机号非法或倒计时子组件显示时,直接返回
  if (!isPhone.value || flag.value) return;
  //开启倒计时模式:倒计时子组件显示
  flag.value = true
  //获取验证码:
  //请求成功:从仓库中拿到用户验证码
  //请求失败:错误处理
  try {
    await userStore.getCode(loginParam.phone)
    loginParam.code = userStore.code
  } catch (error) {
    ElMessage({
      type: "error",
      message: (error as Error).message
    })
  }
}
//点击用户登录按钮的回调
const login = async () => {
  //表单校验:两项都符合条件,才能往下执行;否则返回一个失败的promise对象
  await form.value.validate();
  //点击用户登录按钮的回调
  //请求成功:顶部组件弹出需要展示的用户名字,对话框关闭
  //登陆失败:弹出对应登陆失败的错误信息
  try {
    await userStore.userLogin(loginParam)
    userStore.visible = false
    //如果有曾经想去但是被全局守卫拦截的地址，需要跳转到该地址
    //其余情况就跳转到首页
    let redirect = $route.query.redirect
    if (redirect) {
      $router.push({
        path: redirect as string
      })
    } else {
      $router.push('/home')
    }
  } catch (error) {
    ElMessage({
      type: 'error',
      message: (error as Error).message
    })
  }
}
//手机号码校验函数
//@ts-ignore
const validatorPhone = (rule: any, value: any, callBack: any) => {
  const reg = /^1[3-9]\d{9}$/
  if (reg.test(value)) {
    callBack()
  } else {
    callBack(new Error("请输入正确的手机号码格式"))
  }
}
//验证码校验函数
//@ts-ignore
const validatorCode = (rule: any, value: any, callBack: any) => {
  if (/^\d{6}$/.test(value)) {
    callBack()
  } else {
    callBack(new Error("请输入正确的验证码格式"))
  }
}
//表单校验规则
const rules = {
  //手机号码校验规则
  // phone: [
  //   { require: true, message: '手机号码务必为11位', trigger: 'change', min: 11 }
  // ],
  // code: [
  //   { require: true, message: '验证码务必是6位', trigger: 'blur', min: 6 }
  // ]
  phone: [
    { trigger: 'change', validator: validatorPhone }
  ],
  code: [
    { trigger: 'change', validator: validatorCode }
  ]
}
//对话框关闭事件的回调
const close = () => {
  //清空收集的数据
  Object.assign(loginParam, { phone: '', code: '' })
  //清除上一次校验的结果
  form.value.resetFields()
}
//点击关闭窗口的回调
const closeDialog = () => {
  //当用户仓库中的visible为false时,对话框关闭,close回调就会执行
  userStore.visible = false
}
</script>

<style scoped lang="scss">
.login_container {
  ::v-deep(.el-dialog__body) {
    border-top: 1px solid #ccc;
    border-bottom: 1px solid #ccc;
  }

  .login {
    padding: 20px;
    border: 1px solid #ccc;

    .bottom {
      display: flex;
      flex-direction: column;
      align-items: center;

      p {
        margin: 10px 0;
      }
    }

    .webchat {
      display: flex;
      flex-direction: column;
      align-items: center;

      .phone {
        display: flex;
        flex-direction: column;
        align-items: center;

        p {
          margin: 10px 0;
        }
      }
    }
  }

  .leftContent {
    .top {
      display: flex;
      justify-content: space-around;

      .item {
        display: flex;
        flex-direction: column;
        align-items: center;

        img {
          width: 130px;
          height: 130px;
        }

        p {
          margin: 5px 0;
        }
      }
    }

    .tip {
      text-align: center;
      margin: 20px 0;
      font-size: 20px;
      font-weight: 900;
    }
  }
}
</style>